package ubiqweb.spring3.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import ubiqweb.spring3.model.Registration;
import ubiqweb.spring3.model.LoginDetails;
import ubiqweb.spring3.service.UserService;
import ubiqweb.spring3.model.UserDetails;


@Controller
@RequestMapping("/myProfile.html")
public class ProfileController {
	
	@Autowired
	 private UserService userService;


	// Display the form on the get request
	@SuppressWarnings("unchecked")
	@RequestMapping(method = RequestMethod.GET)
	public String showProfile(Map model, HttpSession session) {
		String userId = session.getAttribute("sessionUsrID").toString();
		List<Registration> registration = userService.listUserDetails(userId);
		UserDetails userDetails = new UserDetails();
		userDetails.setAddress(registration.get(0).getAddress());
		userDetails.setEmail(registration.get(0).getEmail());
		userDetails.setMobileNum(registration.get(0).getMobileNum());
		userDetails.setTelNum(registration.get(0).getTelNum());
		model.put("userDetails", userDetails);
		return "myProfile";
	}

	// Process the form.
	@RequestMapping(method = RequestMethod.POST)
	public String processUserDetails(@Valid UserDetails userDetails,
			BindingResult result, HttpSession session) {
		// set custom Validation by user
		String userId = session.getAttribute("sessionUsrID").toString();
		List<Registration> registration = userService.listUserDetails(userId);
		
		if (result.hasErrors()) {
			return "myProfile";
		}
		registration.get(0).setAddress(userDetails.getAddress());
		registration.get(0).setEmail(userDetails.getEmail());
		registration.get(0).setMobileNum(userDetails.getMobileNum());
		registration.get(0).setTelNum(userDetails.getTelNum());
		
		userService.addUser(registration.get(0));
		
		return "home";
	}
}
